package com.fivefox.attendance.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.fivefox.attendance.service.IPunchCardInfoManage;
import com.fivefox.common.constant.PunchCardInfoManageURL;
import com.fivefox.attendance.domain.UserFlow;
import com.fivefox.common.FeiShuHTTPResult;
import com.fivefox.common.authentication.AccessCredentialsTool;
import org.apache.commons.collections4.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: 李任起
 * @description: 打卡信息管理接口实现类
 * @createDate: 2023-06-28 18:23
 */
@Service
public class PunchCardInfoManageImpl implements IPunchCardInfoManage, PunchCardInfoManageURL {

    private static final Logger logger = LoggerFactory.getLogger(PunchCardInfoManageImpl.class);

    @Autowired
    private AccessCredentialsTool accessCredentialsTool;

    /**
     * 导入打卡流水，打卡流水记录列表(数量限制50)
     *
     * @param employeeType 请求体和响应体中的 user_id 和 creator_id 的员工工号类型
     * @return 返回成功导入数据
     */
    @Override
    public int insertPunchCardRecords(String employeeType, List<UserFlow> userFlowList) {
        /** 统计一共成功导入了多少条数据 */
        int succeedCount = 0;
        /** 拼接URL */
        StringBuilder builderURL = new StringBuilder();
        builderURL.append(IMPORT_PUNCH_CARD_RECORDS_URL);
        builderURL.append("?employee_type=" + employeeType);

        String appAccessToken = accessCredentialsTool.getAppAccessToken();
        /** 循环请求 */
        List<List<UserFlow>> lists = ListUtils.partition(userFlowList, 50);
        for (List<UserFlow> list : lists) {
            String bodyText = UserFlow.getFlowRecords(list);
            String request = HttpRequest.post(builderURL.toString()).body(bodyText).header(Header.AUTHORIZATION, "Bearer " + appAccessToken).execute().body();
            FeiShuHTTPResult resultObj = JSONObject.parseObject(request, FeiShuHTTPResult.class);
            /** 如果导入失败则返回false和记录异常信息 */
            if (resultObj.getCode() != 0) {
                logger.warn("请求导入打卡流水时出现异常：" + request);
            }
            /** 只统计导入成功 */
            if (resultObj.getCode() == 0) {
                succeedCount += list.size();
            }
        }
        return succeedCount;
    }
}
